package org.springframework.beans.factory.support;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.util.*;

/**
 * @Name DefaultListableBeanFactory
 * @Description: Bean 容器 [默认实现] 类
 * 描述信息：该实现类作为 AbstractAutowireCapableBeanFactory、ConfigurableListableBeanFactory 和 BeanDefinitionRegistry 的实现类，具备三者的能力。
 * - AbstractAutowireCapableBeanFactory：支持注入能力的 Bean 容器 [抽象] 类。
 * - ConfigurableListableBeanFactory：基于（Xml）配置的 Bean 容器。
 * - BeanDefinitionRegistry：BeanDefinition 注册表接口。
 * 说明：实现将基于（Xml）配置的 BeanDefinition 信息注册到 BeanDefinition 注册表中，然后基于 BeanDefinition 信息创建 Bean 实例并注入到单例 Bean 实例容器中。
 * @Version v1.0.0
 * @Author: lichao
 * @Date: 2024-03-15 17:01:23
 **/
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry {
    private Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();

    @Override
    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
        beanDefinitionMap.put(beanName, beanDefinition);
    }

    @Override
    public boolean containsBeanDefinition(String beanName) {
        return beanDefinitionMap.containsKey(beanName);
    }

    @Override
    public BeanDefinition getBeanDefinition(String beanName) throws BeansException {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if (beanDefinition == null)
            throw new BeansException("Bean 容器中未找到名称为 [" + beanName + "] 的定义信息");
        return beanDefinition;
    }

    @Override
    public void preInstantiateSingletons() throws BeansException {
        beanDefinitionMap.forEach((beanName, beanDefinition) -> {
            // 只有当 Bean 为单例且不为懒加载时才会被创建
            if (beanDefinition.isSingleton() && !beanDefinition.isLazyInit()) {
                getBean(beanName);
            }
        });
    }

    @Override
    public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
        Map<String, T> result = new HashMap<>();
        beanDefinitionMap.forEach((beanName, beanDefinition) -> {
            Class beanClass = beanDefinition.getBeanClass();
            if (type.isAssignableFrom(beanClass)) {
                T bean = (T) getBean(beanName);
                result.put(beanName, bean);
            }
        });
        return result;
    }

    @Override
    public <T> T getBean(Class<T> requiredType) throws BeansException {
        List<String> beanNames = new ArrayList<>();
        for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
            Class beanClass = entry.getValue().getBeanClass();
            if (requiredType.isAssignableFrom(beanClass)) {
                beanNames.add(entry.getKey());
            }
        }
        if (beanNames.size() == 1) return getBean(beanNames.get(0), requiredType);
        throw new BeansException(requiredType + " 期待为单例 Bean，但是却发现了 " + beanNames.size() + " 个 Bean 实例 [" + beanNames + "]");
    }

    @Override
    public String[] getBeanDefinitionNames() {
        Set<String> beanNames = beanDefinitionMap.keySet();
        return beanNames.toArray(new String[beanNames.size()]);
    }

}

